/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tchepannou.limbe.service.impl;

import com.tchepannou.limbe.Service;
import com.tchepannou.limbe.ServiceContext;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * Abstract implementation of {@link Service}
 *
 * @author Herve Tchepannou
 */
public abstract class AbstractService 
    implements Service
{
    // -- Attribute
    private static final Logger LOG = Logger.getLogger(AbstractService.class.getName());
    private ServiceContext _serviceContext;
    private boolean _initialized;

    // -- Public method
    public ServiceContext getServiceContext ()
    {
        return _serviceContext;
    }

    public boolean isInitialized ()
    {
        return _initialized;
    }

    public <T extends Service> T findService (Class<T> type)
    {
        return _serviceContext.findService (type);
    }

    // -- Service override
    @Override
    public void init (ServiceContext context)
    {
        _serviceContext = context;
        _initialized = true;
    }

    @Override
    public void destroy ()
    {
        _serviceContext = null;
        _initialized = false;
    }

    // -- Protected methods
    protected Properties loadConfigurationAsProperties (String confname)
        throws IOException
    {
        ServletContext context = getServiceContext ().getServletContext ();
        String path = "/WEB-INF/" + confname;
        LOG.info("Loading " + path);
        InputStream in = context.getResourceAsStream(path);
        if (in != null)
        {
            try
            {
                return loadConfigurationAsProperties (in);
            }
            finally
            {
                if ( in != null )
                {
                    in.close ();
                }
            }
        }
        else
        {
            LOG.info(path + " Not found");
            return null;
        }
    }

    protected Properties loadConfigurationAsProperties (InputStream in)
        throws IOException
    {
        Properties p = new Properties ();
        p.load (in);

        for (Object name : p.keySet ())
        {
            LOG.info (" " + name + "=" + p.get (name));
        }

        return p;
    }
}
